<template>
    <div class="main-page">
        <div class="main-btn">
            <el-button  type="success" icon="el-icon-edit" style="text-align:left;">新建台账</el-button>

            <el-button  type="success" style="text-align:left; margin-left: 2%; display: flex; flex-direction: row;" icon="el-icon-upload2" v-show="pdf_name==''">上传报表</el-button>

            <el-button  type="success" icon="el-icon-edit" @click="uploadPDF"  v-show="pdf_name!=''">确认上传</el-button>
            <!-- <el-button  type="success" icon="el-icon-edit" style="text-align:left;" @click="uploadPDF">上传台账</el-button> -->
            <el-button  type="primary" icon="el-icon-folder" style="text-align:right; margin-left: 60%;" v-if="!is_show_all_pdf">查看当月报表</el-button>
            <el-button  type="warning" icon="el-icon-folder" style="text-align:right; margin-left: 60%;" v-if="is_show_all_pdf">查看所有月报表</el-button>
            <el-button  type="warning" icon="el-icon-folder-opened" v-if="!is_show_all" style="text-align:right; margin-left: 2%;">显示所有台账</el-button>
            <el-button  type="primary" icon="el-icon-folder" v-if="is_show_all" style="text-align:right; margin-left: 2%;">显示当月台账</el-button>
        </div>
        <div class="main-page-list"   v-if="sub_department.length<=0">
            <el-table :data="show_pdfs" style="width: 100%;" v-if="pdfs_show">
                <el-table-column prop="pdf_name" label="报表名" width="300">
                </el-table-column>
                <el-table-column label="创建者"  width="200">
                    <template slot-scope="scope">
                        <!-- <el-button type="text" size="small">查看</el-button> -->
                        <p>{{ user_name }}</p>
                    </template>
                </el-table-column>
                <el-table-column prop="date" label="创建日期"  width="200">
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <!-- <el-button type="text" size="small">查看</el-button> -->
                        <el-button type="text" size="small" @click="showPdfBase64(scope.row.pdfbase64)">预览</el-button>
                        <el-button type="text" size="small" style="color: rgb(36, 212, 168);" @click="downloadFile(scope.row.pdf_name,scope.row.pdfbase64)">下载</el-button>
                        <el-button type="text" size="small" style="color: rgb(228, 74, 74);"  @click="deletePdf(scope.row._id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-table
            :data="show_list"
            style="width: 100%;" v-if="!pdfs_show">
                <el-table-column prop="excel_name" label="台账名" width="300">
                </el-table-column>
                <el-table-column label="创建者"  width="200">
                    <template slot-scope="scope">
                        <!-- <el-button type="text" size="small">查看</el-button> -->
                        <p>{{ user_name }}</p>
                    </template>
                </el-table-column>
                <el-table-column prop="date" label="创建日期"  width="200">
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <!-- <el-button type="text" size="small">查看</el-button> -->
                        <el-button type="text" size="small" @click="edit(scope.row.excel_id)">编辑</el-button>
                        <el-button type="text" size="small" style="color: rgb(228, 74, 74);"  @click="deleteExcel(scope.row.excel_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    <el-dialog title="月报表预览" :visible.sync="dialogPdfVisible">
        <div>
            <iframe :src="cur_show_base64" style="width: 800px; height: 800px; border: 1px solid red;">
                <p>您的浏览器不支持  iframe 标签。</p>
            </iframe>
        </div>
    </el-dialog>
    </div>
  </template>
  
  <script>
import {showLoading,hideLoading} from '../components/loading.js'
    export default{
        data(){
            return {
                list:[],
                show_list:[],
                filtrated_list:[],
                user_name:"",
                user_id:"",
                is_show_all:false,
                sub_department:[],
                fileList: [],
                upload_url:"",
                base64:"",
                cur_show_base64:"",
                pdf_name:"",
                pdfs:[],
                pdfs_show:false,
                show_all_pdfs:false,
                dialogPdfVisible: false,
                is_show_all_pdf:false,
                show_pdfs:[],
                filtrated_pdfs:[]
            }
        },
        // mounted(){
        //     this.upload_url="http://"+window.location.hostname+":8888/up_load"
        //     this.user_name=this.$store.state.user_info.department_name
        //     this.user_id=this.$store.state.user_info._id
        //     this.sub_department=this.$store.state.user_info.sub_department
        //     this.getExcelList(this.$store.state.user_info._id);
        // },

        // activated() {
        // },

        // beforeMount(){
        //     this.user_name=this.$store.state.user_info.department_name
        //     this.user_id=this.$store.state.user_info._id
        //     this.getExcelList(this.$store.state.user_info._id);
        // },
        methods:{
          edit(excel_id) {
            this.$router.push({path:'/edit',query:{"excel_id": excel_id}})
          },
          switchShowModel(){
            this.pdfs_show=false
            if(this.is_show_all==false){
                this.is_show_all=true
                this.show_list=this.list
            }else{
                this.is_show_all=false
                this.show_list=this.filtrated_list
            }
          },
          switch_pdf(){
            this.pdfs_show=true
            this.is_show_all_pdf=false
            this.show_pdfs=this.pdfs
          },
          showMonthPdf(){
            showLoading()
            this.pdfs_show=true
            this.is_show_all_pdf=true
            this.$ajax({
                    method: 'post',
                    url: '/get_pdf_by_user_id',
                    data:{"user_id":this.user_id}
                }).
                then(res => {    
                    hideLoading()
                    this.pdfs=res.data
                    let list=res.data
                    let filtrated_pdfs=this.filtrateList(list)
                    this.filtrated_pdfs=filtrated_pdfs
                    this.show_pdfs=filtrated_pdfs
                    this.pdfs_show=true
                });             
          },
          deletePdf(_id){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                showLoading();
                this.$ajax({
                    method: 'post',
                    url: '/delete_pdf__by_id',
                    data:{
                        "pdf_id":_id
                    }
                }).
                then(res => {    
                    hideLoading()
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.showMonthPdf();
                });  
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });           
          },
          showPdfBase64(base64){
            this.cur_show_base64=base64
            this.dialogPdfVisible=true
          },
          getDate(num) {
                var date1 = new Date();
                //今天时间
                var time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
                var date2 = new Date(date1);
                date2.setDate(date1.getDate() + num);
                //num是正数表示之后的时间，num负数表示之前的时间，0表示今天
                var time2 = this.addZero(date2.getFullYear()) + "-" + this.addZero((date2.getMonth() + 1)) + "-" + this.addZero(date2.getDate());
                return time2;
           },
           addZero(num) {//补0方法
                if (parseInt(num) < 10) {
                    num = '0' + num;
                }
                return num;
            },
          uploadPDF(){
            showLoading()
            let date=this.getDate(0)
            this.$ajax({
                    method: 'post',
                    url: '/upload_pdf',
                    data:{
                        "pdf_name":this.pdf_name,
                        "user_id":this.user_id,
                        "user_name":this.user_name,
                        "pdfbase64":this.base64,
                        "date":date
                    }
                }).
                then(res => {    
                    hideLoading()
                    this.fileList = []
                    this.pdf_name=""
                    this.$message({
                        type: 'success',
                        message: '上传成功!'
                    });
            });  
          },
            handleChansge(file) {
                
                if (!/\.(pdf)$/i.test(file.name)) {
                    this.$message.error('只能上传pdf文件!')
                    this.fileList = []
                    this.pdf_name=""
                    return false
                }
                const isLt5M = file.size / 1024 / 1024 <= 5
                if (!isLt5M) {
                    this.$message.error('上传文件大小不能超过 5MB!')
                    this.fileList = []
                    this.pdf_name=""
                    return false
                }
                showLoading()
                let reader = new FileReader();
                
                // let obj={
                //     uid:"",
                //     url:"",
                // }
                // this.fileList.push(obj)
                this.pdf_name=file.name
                reader.readAsDataURL(file.raw);
                var that=this
                reader.onload = function(e){
                    console.log(file)
                    that.base64=this.result
                    hideLoading()
                }
                // setTimeout(()=>{
                //     this.fileList=[]
                // },1000)
            },
            handleRemove() {
                this.resume_url = ''
                this.fileList = []
                this.pdf_name=""
            },
            handleExceed() {
                this.$message.warning(`当前只限制选择 1 个文件`)
            },
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${file.name}？`)
            },
            //根据文件后缀 获取base64前缀 
            getBase64Type (type) {
                switch (type) {
                    case 'txt': return 'data:text/plain;base64,'
                    case 'doc': return 'data:application/msword;base64,'
                    case 'docx': return 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,'
                    case 'xls': return 'data:application/vnd.ms-excel;base64,'
                    case 'xlsx': return 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'
                    case 'pdf': return 'data:application/pdf;base64,'
                    case 'pptx': return 'data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,'
                    case 'ppt': return 'data:application/vnd.ms-powerpoint;base64,'
                    case 'png': return 'data:image/png;base64,'
                    case 'jpg': return 'data:image/jpeg;base64,'
                    case 'gif': return 'data:image/gif;base64,'
                    case 'svg': return 'data:image/svg+xml;base64,'
                    case 'ico': return 'data:image/x-icon;base64,'
                    case 'bmp': return 'data:image/bmp;base64,'
                }
                },
            
            //base64转blob
                base64ToBlob(code) {
                const parts = code.split(';base64,');
                const contentType = parts[0].split(':')[1];
                const raw = window.atob(parts[1]);
                const rawLength = raw.length;
                const uInt8Array = new Uint8Array(rawLength);
                for (let i = 0; i < rawLength; ++i) {
                    uInt8Array[i] = raw.charCodeAt(i);
                }
                return new Blob([uInt8Array], { type: contentType });
                },
            
            //下载
            downloadFile(fileName, content) {
                const blob = this.base64ToBlob(content); // new Blob([content]);
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, fileName);
                } else {
                    const link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = fileName;
            
                    //此写法兼容可火狐浏览器
                    document.body.appendChild(link);
                    const evt = document.createEvent("MouseEvents");
                    evt.initEvent("click", false, false);
                    link.dispatchEvent(evt);
                    document.body.removeChild(link);
                }
                },
            
            //触发下载
            down(){
                this.downloadFile(this.fName,this.getBase64Type(this.fType)+this.fCode)
            
            },
            async upload() {
                // 文件形式的需要用 formData形式
                const formData = new FormData()
                formData.append('file', this.file)
                resumeUpload(formData).then(data => {
                    const { errorCode, data: { path }} = data.data
                    if (errorCode === 0) {
                    this.resume_url = path
                    this.$message.success(`上传成功`)
                    } else {
                    this.filelist = []
                    this.file = ''
                    this.$message.error(`上传失败`)
                    }
                }).catch(err => {
                    console.log(err)
                    this.filelist = []
                    this.file = ''
                    this.$message.error(`上传失败`)
                })
            },
          createExcel(){
                this.$prompt('请输入台账名称', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /^.+$/,
                    inputErrorMessage: '不能为空'
                }).then(({ value }) => {
                    this.$router.push({path:'/create',query:{"excel_name": value}})
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消'
                    });       
                }); 
            },
          deleteExcel(excel_id){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                showLoading();
                this.$ajax({
                    method: 'post',
                    url: '/delete_excel__by_excel_id',
                    data:{
                        "excel_id":excel_id,
                        "user_id":this.user_id
                    }
                }).
                then(res => {    
                    hideLoading()
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getExcelList(this.user_id);
                });  
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
          },
          getExcelList(user_id){
            showLoading();
            this.$ajax({
                method: 'post',
                url: '/get_excel_list_by_user_id',
                data:{
                    "user_id":user_id,
                }
            }).
            then(res => {    
                hideLoading()
                let list=res.data
                this.list=list
                let flit=this.filtrateList(list)
                this.filtrated_list=flit
               this.show_list=flit
            });             
          },
          filtrateList(list){
            var date1 = new Date();
            //今天时间
            var month =date1.getMonth() + 1; 
            let res=[]
            for(let i=0;i<list.length;i++){
                let d=list[i].date
                let m=d.split("-")[1]
                m=parseInt(m)
                if(m==month){
                    res.push(list[i])
                }
            }
            return res
        }
        },

  
    }
  </script>
  
  
  <style>
    .main-page{
      width: 100%;
      height: 80vh;
      padding: 1vh;
    }
    .main-page-list{
      margin-top:1vh;
      width: 100%;
      height: 70vh;
      overflow-y: scroll;
    }
    .main-btn{
        width: 100%;
        display: flex;
        margin-top:1vh;
        margin-bottom:1vh;
    }
  </style>
  
  